<template>
  <template v-if="componentsData?.name">
    <view
      class="body"
      :style="{
        backgroundImage: `url(${componentsData.bgUrl})`,
        height: px2rpx2px(componentsData.bgImgHeight),
        backgroundColor: `${componentsData.bgColor}`,
      }"
    >
      <template
        v-for="(item, index) in componentsData.componentList"
        :key="index"
      >
        <custom-card
          class="home-data"
          v-if="item.d.name === 'CustomCard'"
          :info="userInfo"
          v-bind="item.d"
          @onCardClick="onCardClick"
          @onIntegralClick="handleToExchange"
        />
        <title-text
          class="home-data"
          v-if="item.d.name === 'TitleText'"
          v-bind="item.d"
        />
        <custom-image
          class="home-data"
          v-if="item.d.name === 'CustomImage'"
          v-bind="item.d"
          @onHotZoneClick="onHotZoneClick"
        />
        <custom-banner
          class="home-data"
          v-if="item.d.name === 'CustomBanner' && isHome"
          v-bind="item.d"
          @onHotZoneClick="onHotZoneClick"
          @onLink="onLink"
          @videoPlay="handleVideoPlay"
          @videoChange="handleVideoChange"
          @imageChange="handleBannerImageChange"
        />
        <custom-dialog
          class="home-data"
          v-if="item.d.name === 'CustomDialog'"
          v-bind="item.d"
          @onHotZoneClick="onHotZoneClick"
          @close="handleDialogClose"
          @view="onCustomDialogView"
        />
        <birthday-dialog
            v-if="state.birthdayDialog"
            @close="handleChangeBirthdayDialog(false)"
        ></birthday-dialog>
      </template>
    </view>
  </template>

  <button open-type="contact" @click.stop="toKefu">
    <view class="oreo-service">
      <image :src="ossImg('personal/kf_icon@2x.png')" />客服
    </view>
  </button>
  <custom-tab-bar :current="0" :cartCount="cartCount" />
  <add-tip :tip="'点击“···”添加到我的小程序👆\n玩心福利天天领'" />
  <!-- 隐私协议 -->
  <!-- <privacyPopup @agreePrivacy="agreePrivacy"></privacyPopup> -->
</template>

<script setup>
import { ossImg, message } from "@/utils/utils";
import {reactive, ref} from "vue";
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { setCurrentTabBar } from "@/utils/utils";
import addTip from "@/components/struggler-uniapp-add-tip/struggler-uniapp-add-tip.vue";

import TitleText from "../../oreo-custom-components/TitleText";
import CustomImage from "../../oreo-custom-components/CustomImage";
import CustomBanner from "../../oreo-custom-components/CustomBanner";
import CustomCard from "../../oreo-custom-components/CustomCard";
import CustomDialog from "../../oreo-custom-components/CustomDialog";
import CustomTabBar from "@/components/custom-tab-bar";
import birthdayDialog from "@/components/birthday-dialog.vue";
import { px2rpx2px } from "../../oreo-custom-components/utils/index";
import { getDecorationInfo } from "@/services/home";
import { addCoupon } from "@/services/coupon";
import BirthdayDialog from "@/components/birthday-dialog";

let enterTime = "";
let outTime = "";
let stayTime = "";

const value = ref('');
const userInfo = ref({});
const cartCount = ref(getApp().globalData.cartCount);
const isDialog = ref(false);
const componentsData = ref({});
const emdlz = getApp().emdlz2

const isHome = ref(false)

const state = reactive({
  birthdayDialog: false,
})

const handleChangeBirthdayDialog = (visible) => {
  if (visible) {
    //
  } else {
    //
  }
  state.birthdayDialog = visible
}

onLoad(async (options) => {
  //获取二维码的携带的链接信息
  // console.log(options, uni.getStorageSync("TOKEN"));
  switch (true) {
    case [1044, 1007, 1008].includes(uni.getLaunchOptionsSync().scene):
      if (options.id) uni.setStorageSync("inviterId", options.id);
      break;
    default:
      console.log("LaunchOptionsSync", uni.getLaunchOptionsSync());
      break;
  }
  isDialog.value = true;
});
onShow(() => {
  isHome.value = getCurrentPages().at(-1).route === 'pages/home/home'
  if (uni.getStorageSync("TOKEN")) {
    getApp()
      .getUserInfo()
      .then((res) => {
        userInfo.value = res;
      });
    getApp()
      .getCartCount()
      .then((res) => {
        cartCount.value = res;
      });
    getHomeInfo();
  } else {
    userInfo.value = {}
  }
  setCurrentTabBar(0);
  // 用户进入时间
  enterTime = new Date();
  /* 未满14岁生日提醒 */
  let birthday = getApp().globalData.user.birthday;
  if (birthday !== null && birthday !== undefined && birthday !== '') {
    const birth = new Date(birthday);
    const today = new Date();
    // 计算年龄
    let age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();

    // 如果当前月份小于出生月份，或者月份相同但当前日期小于出生日期，则年龄减1
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
      age--;
    }
    if (age < 14) {
      handleChangeBirthdayDialog(true)
    }
  }
  /* END */
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  console.log("页面隐藏" + ":" + stayTime + "s");
  emdlz('track','event','standardized_components','view','page_view_home', `${stayTime}`);
  getApp().accessLogAdd();
  getApp().emdlz2(
    "track",
    "event",
    "homepage_new",
    "view",
    "firstpage",
    stayTime
  );
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
  emdlz('track','event','standardized_components','view','page_view_home', `${stayTime}`);
  getApp().accessLogAdd();
  getApp().emdlz2(
    "track",
    "event",
    "homepage_new",
    "view",
    "firstpage",
    stayTime
  );
});

onShareAppMessage((e) => {
  var shareTitle = "一起参加现金红包抽奖活动";
  var sharePath = "pages/home/home";
  var shareImage =
    "https://scrm2-prod.oss-accelerate.aliyuncs.com/upload/material/0f99a0e1-1534-4e42-964d-ca6b96e1571b.jpg";
  if (componentsData.value.shareInfo.imageUrl) {
    shareTitle = componentsData.value.shareInfo.title;
    sharePath = componentsData.value.shareInfo.path;
    shareImage = componentsData.value.shareInfo.imageUrl;
  }
  const shareObj = {
    title: shareTitle, // 默认是小程序的名称(可以写slogan等)
    path: sharePath, // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: shareImage, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});

// dialog view
const onCustomDialogView = () => {
  emdlz('track','event','standardized_components','view','tips_page','');
}

const handleVideoPlay = ({ vid, process }) => {
  if (!process) return
  emdlz('track','event','standardized_components','click', `vedio_playback_${vid}`, process);
}

const handleVideoChange = ({ vid }) => {
  emdlz('track','event','standardized_components','slide',`banner_vedio_${vid}`,'');
}

const handleBannerImageChange = ({ vid }) => {
  emdlz('track','event','standardized_components','slide',`banner_image_${vid}`,'');
}

const handleDialogClose = ({ vid }) => {
  emdlz('track','event','standardized_components','click',`close_pop_up_${vid}`,'');
}

const getHomeInfo = async () => {
  if (componentsData.value?.name) return
  const res = await getDecorationInfo({ scope: 2 });
  if (res?.code === 200) {
    const components = JSON.parse(res?.data.config) ?? [];
    componentsData.value = components;
  }
};

const getCoupon = async (id) => {
  const res = await addCoupon({
    ...{ couponId: id, appId: process.env.WXAPPID },
  });
  if (res?.code === 200) {
    message(res.message);
  }
};

const onHotZoneClick = ({
  url,
  isCoupon,
  redirect = true,
  currentVideo = null,
  vid, uniqueId, dialog = false
}) => {
  if (typeof currentVideo === 'number') {
    emdlz('track','event','standardized_components','click',`open_vedio_${vid}`,'');
  } else if (dialog) {
    // 自定义弹窗点击回传
    emdlz('track','event','standardized_components','click','tips_click','');
  } else {
    emdlz('track','event','standardized_components','click',`multifunction_link_image_${vid}_${uniqueId}_${isCoupon ? 'coupon': 'page'}_${url}`,'');
  }
  // to do
  if (isCoupon) {
    getCoupon(url);
  } else {
    // 不需要强制注册用户的path
    const noRegisterPaths = ['/campaign/pages/oreo-destiny/index', '/campaign/pages/2025OreoStayPlayful/index']
    if (noRegisterPaths.includes(url.split('?')?.[0])) {
      console.log('noRegisterPaths-redirect')
      uni.redirectTo({
        url: currentVideo === null ? url : url?.split(",")[currentVideo],
      });
      return
    }
    // 页面路径跳转方式处理
    switch (true) {
      // 无需授权页面路径
      case ["/pages/home/home", "/pages/mall/mall"].includes(
        currentVideo === null ? url : url?.split(",")[currentVideo]
      ):
        uni.switchTab({
          url: currentVideo === null ? url : url?.split(",")[currentVideo],
        });
        break;

      case ["/integralPages/integral/integral"].includes(url):
        uni.redirectTo({
          url: currentVideo === null ? url : url?.split(",")[currentVideo],
        });
        break;

      case ["/pages/cart/cart", "/pages/personal/personal"].includes(url):
        uni.switchTab({
          url: currentVideo === null ? url : url?.split(",")[currentVideo],
        });
        break;

      case ["/pages/goods/goods", "/pages/webView/webview"].includes(
        currentVideo === null
          ? url?.split("?")[0]
          : url?.split(",")[currentVideo].split("?")[0]
      ):
        console.log(url);
        uni.navigateTo({
          url: currentVideo === null ? url : url?.split(",")[currentVideo],
        });
        break;

      default:
        // 需要授权页面路径
        if (
          getApp().globalData.user.nickname === null ||
          getApp().globalData.user.nickname === "" ||
          getApp().globalData.user.nickname === undefined
        ) {
          return getApp().getWechatUserProfile({ url, redirect: true });
        }
        if (
          getApp().globalData.user.phone === null ||
          getApp().globalData.user.phone === ""
        ) {
          uni.setStorageSync(
            "REDIRECT_URI",
            JSON.stringify({
              url: currentVideo === null ? url : url?.split(",")[currentVideo],
              redirect: true,
            })
          );
          uni.navigateTo({ url: "/pages/vip/register" });
          return;
        }
        uni.redirectTo({
          url: currentVideo === null ? url : url?.split(",")[currentVideo],
        });

        break;
    }
  }
};

const onCardClick = () => {
  if (
    getApp().globalData.user.nickname === null ||
    getApp().globalData.user.nickname === "" ||
    getApp().globalData.user.nickname === undefined ||
    getApp().globalData.user.phone === null ||
    getApp().globalData.user.phone === "" ||
    getApp().globalData.user.phone === undefined
  ) {
    getApp().getWechatUserProfile({
      path: "/pages/home/home",
    });
  }
};

const handleToExchange = () => {
  const path = "/personalPages/biscuit/mall";

  emdlz('track','event','standardized_components','click','points_portal','');
  getApp().emdlz2("track", "event", "homepage_new", "click", "Points_Mall", "");

  if (
    getApp().globalData.user.phone === null ||
    getApp().globalData.user.phone === ""
  ) {
    console.log(0);
    uni.setStorageSync(
      "REDIRECT_URI",
      JSON.stringify({ path, redirect: true })
    );
    uni.navigateTo({ url: "/pages/vip/register" });
    return;
  }
  if (
    getApp().globalData.user.nickname === null ||
    getApp().globalData.user.nickname === "" ||
    getApp().globalData.user.nickname === undefined
  ) {
    return getApp().getWechatUserProfile({ path, redirect: true });
  }
  uni.navigateTo({ url: path });
};

const onLink = ({ link, vid }) => {
  emdlz('track','event','standardized_components','click',`open_image_${vid}`,'');
  const _link = link.includes("?") ? `${link}&banner=1` : `${link}?banner=1`
  if (link.includes('pages/formula/formula')) {
    uni.switchTab({ url: _link })
    return
  }
  setTimeout(() => uni.navigateTo({ url: _link }), 200)
};

const closeDialog = () => {
  isDialog.value = false;
  getApp().emdlz2("track", "event", "homepage_new", "click", "Popup_close", "");
};

const toKefu = () => {
  getApp().emdlz2("track", "event", "homepage", "click", "customer_service", "");

  getApp().sr().track("start_consult", {
    action_type: "consult_online",
    // more...
  });
};

const linkTo = (url) => uni.navigateTo({ url });
const toBuy = () => {
  getApp().emdlz2(
    "track",
    "event",
    "homepage_new",
    "click",
    "Popup_buy_now",
    ""
  );
  linkTo(`/pages/goods/goods?id=${"703965fe7f9fe4ee592f74b70c354a63"}`);
};

setTimeout(() => (value.value = 1), 3000);

const agreePrivacy = () => {};
</script>

<style lang="less" scoped>
:deep(.uni-add-tips-content) {
  background-color: #0057d1 !important;
  font-size: 12px !important;
  margin-right: 10px !important;
  padding: 5px !important;
}
:deep(.uni-add-tips-content::before) {
  border-color: transparent transparent #0057d1 transparent !important;
  border-bottom-color: #0057d1 !important;
}

.body {
  width: 100%;
  min-height: 100vh;
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 375px 100%;
  position: relative;
}
.mode {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.63);

  .bg_img {
    width: 100%;
    height: 450px;
    position: absolute;
    top: 14vh;
    image {
      width: 100%;
      height: 100%;
    }

    .buy {
      width: 170px;
      height: 108rpx;
      position: absolute;
      left: 102px;
      bottom: 6px;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 170px 108rpx;
    }

    .close {
      width: 32px;
      height: 32px;
      position: absolute;
      top: -16px;
      right: 31.5px;
    }
  }
}
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
.off-acc {
  width: 100%;
  height: 100px;
}
</style>
